<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
description("Tests bad algorithm inputs for AES-CTR");

jsTestIsAsync = true;

var keyData = hexStringToUint8Array("2b7e151628aed2a6abf7158809cf4f3c");
var data = asciiToUint8Array("hello");
var key = null;
var counter = new Uint8Array(16);
var kExpectedCipherTextHex = "1592076075";
var kLength = 8;

function corruptCounter()
{
    debug("Neutering counter...");
    try { postMessage(counter, "xxx", [counter.buffer]); } catch (e) { }
    shouldBe("counter.byteLength", "0");
}

Promise.resolve(null).then(function(result) {
    var usages = ['encrypt', 'decrypt'];
    var extractable = false;

    debug("\nImporting AES-CTR key...");
    return crypto.subtle.importKey('raw', keyData, "aes-ctr", extractable, usages);
}).then(function(result) {
    key = result;

    debug("\nencrypt() with normal data (control group)...");
    return crypto.subtle.encrypt({name: 'AES-CTR', counter: counter, length: kLength}, key, data);
}).then(function(result) {
    bytesShouldMatchHexString("Encryption", kExpectedCipherTextHex, result);

    var algorithm = {
        name: 'AES-CTR',

        get counter() {
            debug("Accessed counter");
            return counter;
        },

        get length() {
            debug("Accessed length");
            corruptCounter();
            return kLength;
        }
    };

    return crypto.subtle.encrypt(algorithm, key, data);
}).then(function(result) {
    bytesShouldMatchHexString("Encryption", kExpectedCipherTextHex, result);

}).then(finishJSTest, failAndFinishJSTest);

</script>

</body>
</html>
